<template>
  <div class="app-container">
    <!-- 搜索 -->
    <div style="padding-bottom: 10px">
      <el-page-header @back="goBack" :content="getTitle"> </el-page-header>
    </div>
    <el-card>
      <el-form
        size="small"
        :model="form"
        :rules="formRules"
        ref="formRef"
        label-width="120px"
        label-position="right"
        style="width: 95%"
      >
        <el-row>
          <el-col :span="8">
            <el-form-item label="商品名称" prop="name">
              <el-input v-model="form.name" placeholder="商品名称" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="商品SN" prop="sn">
              <el-input v-model="form.sn" placeholder="商品SN" clearable />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="商品分类" prop="category">
              <el-select
                v-model="form.category"
                placeholder="商品分类"
                clearable
              >
                <el-option
                  v-for="item in categories"
                  :label="item.name"
                  :value="item.id"
                  :key="item.id"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="商品价格" prop="price">
              <el-input v-model="form.price" placeholder="商品SN" clearable>
                <el-button slot="append" type="default">元</el-button>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="库存量" prop="stock_nums">
              <el-input
                v-model="form.stock_nums"
                placeholder="商品库存"
                clearable
              >
                <el-button slot="append" type="default">件</el-button>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="是否下架" prop="drop">
              <el-select v-model="form.drop" placeholder="是否下架">
                <el-option
                  v-for="item in drops"
                  :label="item.label"
                  :value="item.value"
                  :key="item.value"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="顺序" prop="sort">
              <el-input v-model="form.sort" placeholder="顺序" clearable>
              </el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="产品说明">
          <tinymce v-model="form.content" :height="380" />
        </el-form-item>
        <el-form-item label="产品图片" v-if="goods_id > 0">
          <el-upload
            ref="upload"
            name="image"
            action="/api/shopping/image_upload/"
            multiple
            :on-preview="handlePreview"
            :before-upload="handleBeforeUpload"
            :on-remove="handleRemove"
            :on-success="handleSuccess"
            :file-list="fileList"
            accept=".jpg, .jpeg, .png, .gif, .JPG, .JPEG, .PNG, .GIF"
            :headers="headerObj"
            :data="uploadData"
            list-type="picture-card"
          >
            <i class="el-icon-plus"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="">
          <div>
            <el-button @click="goBack" size="medium">返回</el-button>
            <el-button type="primary" @click="handleSave(false)" size="medium"
              >保存</el-button
            >
            <el-button type="success" @click="handleSave(true)" size="medium"
              >保存后上传图片</el-button
            >
          </div>
        </el-form-item>
      </el-form>
    </el-card>
    <!-- 图片上传 -->
    <el-dialog
      :visible.sync="dlgUploadVisible"
      title="商家图片"
      width="800px"
      destroy-on-close
      @close="handleClose"
    >
      <el-form
        label-width="100px"
        :model="uploadForm"
        label-position="right"
        style="width: 95%; padding: 0 30px"
        status-icon
      >
        <el-form-item label="商品名称">
          <el-input v-model="uploadForm.name" size="small" disabled></el-input>
        </el-form-item>

        <el-form-item label="商品图片">
          <el-upload
            ref="upload"
            name="image"
            action="/api/shopping/image_upload/"
            multiple
            :on-preview="handlePreview"
            :before-upload="handleBeforeUpload"
            :on-remove="handleRemove"
            :on-success="handleSuccess"
            :file-list="fileList"
            accept=".jpg, .jpeg, .png, .gif, .JPG, .JPEG, .PNG, .GIF"
            :headers="headerObj"
            :data="uploadData"
            list-type="picture-card"
          >
            <i class="el-icon-plus"></i>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="dlgUploadVisible = false" size="mini"
          >关闭</el-button
        >
      </div>
      <el-dialog :visible.sync="dlgImageVisible" append-to-body>
        <el-image
          style="width: 100%; min-height: 400px"
          :src="dlgImageUrl"
          fit="fill"
        ></el-image>
        <div slot="footer">
          <el-button @click="dlgImageVisible = false" size="mini"
            >关闭</el-button
          >
        </div>
      </el-dialog>
    </el-dialog>
  </div>
</template>

<script>
import { mapGetters } from "vuex";
import Tinymce from "@/components/Tinymce";
import {
  getCategories,
  getGoodsById,
  updateGoods,
  addGoods,
  delGoodsImage,
} from "@/api/shopping";

const defaultForm = {
  id: null,
  name: null,
  sn: null,
  category: null,
  price: "",
  content: null,
  stock_nums: "",
  is_new: "",
  is_hot: "",
  catclick_nums: 0,
  drop: 0,
  sort: 0,
  user: null,
};

export default {
  name: "GoodsAdd",
  components: {
    Tinymce,
  },
  props: ["goods_id"],
  data() {
    return {
      form: Object.assign({}, defaultForm),

      formRules: {
        name: [{ required: true, message: "请输入商品名称", trigger: "blur" }],
        sn: [{ required: true, message: "请输入商品SN", trigger: "blur" }],
        category: [{ required: true, message: "请商品分类", trigger: "blur" }],
        // price: [{ required: true, message: "请输入商品价格", trigger: "blur" }],
        stock_nums: [
          { required: true, message: "请输入库存量", trigger: "blur" },
        ],
      },
      title: "商品信息",
      categories: [],
      uploadForm: {
        name: "",
        goods_id: null,
        images: [],
      },
      fileList: [],
      dlgUploadVisible: false,
      dlgImageVisible: false,
      dlgImageUrl: "",

      drops: [
        { value: 0, label: "无" },
        { value: 1, label: "下架" },
      ],
    };
  },
  computed: {
    ...mapGetters(["uid", "token"]),
    getTitle() {
      return this.goods_id == undefined
        ? `新增${this.title}`
        : `修改${this.title}`;
    },
    headerObj() {
      return {
        authorization: "JWT " + this.token,
      };
    },
    uploadData() {
      return {
        goods_id: this.goods_id,
      };
    },
  },
  mounted() {
    this.getCategoryList();
    this.getGoodsInfo();
  },
  methods: {
    //商品分类
    getCategoryList() {
      getCategories()
        .then((res) => {
          this.categories = res;
        })
        .catch((error) => {
          console.log(error.message);
        });
    },
    getGoodsInfo() {
      if (this.goods_id > 0) {
        getGoodsById(this.goods_id)
          .then((res) => {
            console.log(res);
            this.form = res;
            this.fileList = res.images.map((item) => {
              return {
                name: item.name,
                url: item.image,
                id: item.id,
              };
            });
          })
          .catch((err) => {
            this.$message.error("读取详细信息失败");
          });
      }
    },
    goBack() {
      this.$router.go(-1);
    },
    ///上传图片
    handleUpload(row) {
      this.dlgUploadVisible = true;
      this.uploadForm.goods_id = row.id;
      this.uploadForm.name = row.name;
      this.uploadForm.images = row.images;

      // this.fileList = this.uploadForm.images.map((item) => {
      //   return {
      //     name: item.name,
      //     url: item.image,
      //     id: item.id,
      //   };
      // });
    },
    //上传前
    handleBeforeUpload(file) {
      const flag = file.size / 1024 / 1024 < 10;
      if (!flag) {
        this.$message.error("上传文件大小不能超过 10MB!");
      }
      return flag;
    },
    // 预览
    handlePreview(file) {
      this.dlgImageUrl = file.url;
      this.dlgImageVisible = true;
    },
    handleSuccess(res, file, filelist) {
      this.fileList = filelist;
      if (res.status_code == 200) {
        this.uploadForm.images.push(file.response.file);
        this.$message.success("图片上传成功");
      } else {
        this.$message.error("上传失败");
      }
    },
    //图片删除
    handleRemove(file, fileList) {
      this.fileList = fileList;
      var file_id = null;
      file_id = file.id;
      if (file_id == null) {
        if (file.response.status_code == 200) {
          file_id = file.response.file.id;
        }
      }

      if (file_id == null) return;

      delGoodsImage(file_id)
        .then((res) => {
          const index = this.uploadForm.images.findIndex(
            (item) => item.id == file_id
          );
          if (index > -1) {
            this.uploadForm.images.splice(index, 1);
          }
          this.$message.success("删除成功");
        })
        .catch((error) => {
          this.$message.error("删除失败");
        });
    },
    //关闭对话框
    handleClose() {},
    async handleSave(flag) {
      this.$refs.formRef.validate(async (valid) => {
        if (!valid) return;

        let res = null;
        if (this.goods_id == undefined) {
          this.form.user = this.uid;
          try {
            res = await addGoods(this.form);
          } catch (err) {
            this.$message.error("增加失败!");
          }
        } else {
          if (!this.form.user) {
            this.form.user = this.uid;
          }
          try {
            res = await updateGoods(this.form);
          } catch (err) {
            console.log(err);
            this.$message.error("修改失败!");
          }
        }
        if (flag) {
          this.form = res;
          if (this.goods_id == undefined) {
            this.goods_id = res.id;
          }
          const row = {
            id: res.id,
            name: res.name,
            images: res.images,
          };
          this.handleUpload(row);
          return;
        }
        this.$router.push("/shopping/goods");
        const { name, category_name, price } = res;

        this.$notify({
          title: "Success",
          dangerouslyUseHTMLString: true,
          message: `
              <div>商品名称: ${name}</div>
              <div>商品分类: ${category_name}</div>
              <div>商品价格: ${price}</div>
            `,
          type: "success",
        });
      });
    },
  },
};
</script>

<style  scoped>
</style>